package com.tbit.uqbike.service.rpcservice.impl;

import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.service.base.RedisService;
import com.tbit.uqbike.service.rpcservice.SmsService;
import com.tbit.uqbike.webmanager.config.ManagerConfig;
import com.tbit.uqbike.webmanager.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019-12-09 13:37
 */
public abstract class BaseSmsService implements SmsService {

    @Autowired
    private RedisService redisService;

    @Override
    public Map<String, Object> sendCode(String country, String phone, String code, String type, Map<String, Object> param) {
        LoginInfo li = SmsService.getAttr(param, "info", LoginInfo.class);
        String content;
        // type合法性判定
        if (Objects.equals(type, SmsService.CODE_LOGIN)) {
            content = li.context.getMessage("login_sms_content_format", new Object[]{code});
        } else {
            throw new BaseException(SystemCodeEnum.NOT_SUPPORT_SMS_CODE);
        }

        LogUtil.info(phone + "=" + content);

        // 检测是否存在，如果存在不允许发送
        String existCode = redisService.get(SmsService.getCodeRedisKey(country, phone, type));
        if (StringUtils.isEmpty(existCode)) {
            // 发送
            sendSms(country, phone, content, param);
            // 记录缓存
            redisService.add(SmsService.getCodeRedisKey(country, phone, type), code, ManagerConfig.LoginCodeSec);
            return new HashMap<>();
        } else {
            throw new BaseException(SystemCodeEnum.SMS_CODE_ALREADY_VALID);
        }
    }
}
